<?php

namespace App\Http\Controllers;

use App\Models\Clue;
use App\Models\MediaSource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\File;

class ClueController extends Controller
{

    public function store(Request $request)
    {
        Log::debug("手动提交线索 :", $request->all());
        $data = $request->only(['name', 'phone', 'source', 'question_data', 'url', 'ip', 'location', 'ad_name', 'remark']);

        $url = data_get($data, 'url');
        if (!$url)
            return response()->json([
                'code' => HTTP_EMPTY_URL,
                'message' => 'Url为空',
            ])->setStatusCode(400);

        if (strlen($url) > 1781) {
            $url = substr($url, 0, 1781);
        }

        if (!$source = data_get($data, 'source')) {
            if (!$source = Clue::getSourceByUrl($url))
                return response()->json([
                    'code' => HTTP_EMPTY_SOURCE,
                    'message' => '来源为空.'
                ])->setStatusCode(400);
        }
        $keys = MediaSource::toKeyOptions();
        if (!in_array($source, $keys))
            return response()->json([
                'code' => HTTP_UNKNOWN_SOURCE,
                'message' => '未适配或者错误的来源.'
            ])->setStatusCode(400);

        $data['source'] = $source;
        $phone = data_get($data, 'phone');
        if (!$phone || !preg_match("/^1[3-9]\d{9}$/", $phone))
            return response()->json([
                'code' => HTTP_ERROR_PHONE,
                'message' => '错误的电话号码.'
            ])->setStatusCode(400);
        if (!Cache::get($phone)) {
            $ip = data_get($data, 'ip');
            if (!$ip || $ip === '127.0.0.1') {
                $data['ip'] = $ip = $request->getClientIp();
            }
            $location = data_get($data, 'location', data_get($data, 'city'));
            if (!$location || $location === '未知') {
                $ipData = geoip($ip)->toArray();
                $data['location'] = data_get($ipData, 'state_name', '') . data_get($ipData, 'city', '');
            }
            $query = data_get($data, 'question_data');
            if (is_string($query))
                $query = json_decode($query, true) ?? [];
            $data['question_data'] = $query;
            $data['type'] = Clue::TYPE_API;
            $data['post_date'] = now();
            Clue::create($data);
            Cache::put($phone, $source, $data['post_date']->endOfDay());
        }

        return response()->json([
            'code' => HTTP_OK,
            'message' => 'OK.'
        ]);
    }

    public function handleClue(Request $request)
    {
        $source = $request->get('source', $request->get('_source_'));
        Log::debug("接受数据 '$source':", $request->all());

        if (!$source)
            return response()->json([
                'code' => HTTP_EMPTY_SOURCE,
                'message' => 'error:  source field is required.',
            ])->setStatusCode(404);

        if ($source === 'source')
            return [
                'code' => HTTP_OK,
            ];

        $response = [
            'code' => HTTP_OK,
            'message' => 'success',
        ];
        $data = null;
        switch ($source) {
            case"华为":
                dd($request->all());
                return '测试';
                $data = '';
                break;
            case "巨量":
            case "飞鱼":

                $data = parserJuLiangRequest($request);
                break;
            case "基木鱼":
            case "百度":
                $data = parserBaiduRequest($request);
                break;
            case "快手":
                $data = parserKuaiShouRequest($request);
                $response = [
                    'code' => '0',
                ];
                break;
            case "腾讯":
            case "广点通":
                $data = parserTengXunRequest($request);
                break;
            default:
                break;
        }

        if (!$data)
            return response()->json([
                'code' => HTTP_UNKNOWN_REQUEST,
                'message' => 'error: cannot parse request or unknown source',
            ])->setStatusCode(404);
        $phone = $data['phone'];
        $key = Cache::get($phone);
        Log::debug("判断是否重复", [
            'phone' => $phone,
            'key' => $key,
            'source' => $source,
        ]);
        if ($key) {
            if ($key == $source)
                return response()->json($response);
            $data['no_dispatch'] = 1;
        } else
            Cache::put($phone, $source, today()->endOfDay());

        Clue::updateOrCreate([
            'source' => $data['source'],
            'uuid' => $data['uuid']
        ], $data);
        return response()->json($response);
    }

    public function buyClueIndex(Request $request)
    {
        $id = $request->get('id');
        $source = $request->get('source');
        if (!$id || !$source)
            return response()->json([
                'code' => 1,
                'msg' => '错误的参数'
            ]);

        $list = Clue::query()
            ->select([
                'name',
                'phone',
                'source',
                'question_data',
                'site_name',
                'location',
                'files',
                'post_date',
            ])
            ->where('source', $source)
            ->where('site_name', $id)
            ->whereDate('post_date', '>=', today()->addDays(-2))
            ->orderBy('post_date', 'desc')
            ->get()
            ->map(function ($item) {
                return [
                    'name' => $item['name'],
                    'phone' => $item['phone'],
                    'remark' => $item['question_data'],
                    'address' => $item['location'],
                    'files' => Storage::disk('public')->url($item['files']),
                    'date' => $item['post_date'],
                ];
            });
        return response()->json([
            'code' => 0,
            'data' => $list,
            'msg' => "OK",
        ]);
    }

    public function buyClueStore(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'phone' => 'required|regex:/^1[3456789]\d{9}$/',
            'name' => 'required|max:10',
            'address' => 'required|max:20',
            'remark' => 'required|max:200',
            'files' => 'required|max:200',
            'url' => 'required|max:100',
            'source' => 'required|exists:media_sources,id',
        ], [
            'phone.required' => '电话不能为空',
            'phone.regex' => '电话格式错误',
            'name.required' => '姓名不能为空',
            'address.required' => '姓名不能为空',
            'remark.required' => '姓名不能为空',
            'files.required' => '姓名不能为空',
            'url.required' => '类型不能为空',
            'source.required' => '来源不能为空',
            'source.exists' => '来源不存在',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 1,
                'field' => $validator->messages(),
                'msg' => '参数错误'
            ]);
        }

        $data = $request->only(['phone',
            'name',
            'address',
            'remark',
            'files',
            'wechat',
            'url',
            'source',]);
        if (Cache::get($data['phone'])) {
            return response()->json([
                'code' => 1,
                'msg' => '该号码今日重单'
            ]);
        }
        Clue::create([
            'name' => $data["name"],
            'phone' => $data["phone"],
            'source' => $data["source"],
            'question_data' => $data["remark"],
            'site_name' => $data["url"],
            'location' => $data["address"],
            'files' => $data["files"],
            'type' => Clue::TYPE_GRAB,
            'post_date' => now(),
        ]);
        Cache::put($data['phone'], $data['source'], now()->endOfDay());

        return response()->json([
            'code' => 0,
            'msg' => '创建完成'
        ]);


    }

    public function clueStoreApi(Request $request)
    {
        if (!admin_setting('enable_clue_api'))
            return abort(404);
        $key = '3322123';
        $source_id = my_decrypt($request->get('k'), $key);

        if (!is_numeric($source_id) || !MediaSource::query()->select(['id'])->where('id', $source_id)->exists())
            return abort(404);

        $validator = Validator::make($request->all(), [
            'phone' => 'required|regex:/^1[3456789]\d{9}$/',
            'name' => 'required|max:10',
            'address' => 'required|max:20',
            'remark' => 'required|max:200',
            'files' => [
                'required',
                File::types(['mp3', 'wav', 'ogg'])->max(12 * 1024)
            ],
        ], [
            'phone.required' => '电话不能为空',
            'phone.regex' => '电话格式错误',
            'name.required' => '姓名不能为空',
            'address.required' => '所在地不能为空',
            'remark.required' => '备注不能为空',
            'files.required' => '录音文件不能为空',
            'files.mimes' => '只接受mp3,wav,ogg格式',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => HTTP_UNKNOWN_REQUEST,
                'field' => $validator->messages(),
                'msg' => '参数错误'
            ]);
        }
        $path = $request->file('files')->store('clue_files', ['disk' => 'public']);
        if (!$path)
            return response()->json([
                'code' => HTTP_UNKNOWN_REQUEST,
                'msg' => '错误的文件'
            ]);

        $data = $request->only([
            'phone',
            'name',
            'address',
            'remark',
            'wechat',
        ]);

        if (Cache::get($data['phone'])) {
            return response()->json([
                'code' => HTTP_OK,
                'msg' => '该号码今日重单'
            ]);
        }
        Clue::create([
            'name' => $data["name"],
            'phone' => $data["phone"],
            'source' => $source_id,
            'question_data' => $data["remark"],
            'location' => $data["address"],
            'files' => $path,
            'type' => Clue::TYPE_GRAB,
            'post_date' => now(),
        ]);
        Cache::put($data['phone'], $source_id, now()->endOfDay());

        return response()->json([
            'code' => HTTP_OK,
            'msg' => '创建完成'
        ]);


    }
}
